import qs from 'qs'
import * as auth from "../auth-provider";
import { useAuth } from "../context/auth-context";
import { useCallback } from "react";
const appUrl= process.env.REACT_APP_API_URL

interface Config extends RequestInit{
  token?: string,
  data?: object
}

// 封装fetch请求
export const http = async (endpoint: string, {data, token, headers, ...customConfig}: Config = {}) => {
  const config = {
    method: "GET",
    headers: {
      Authorization: token ? `Bearer ${token}` : '',
      'Content-Type': data?'application/json':''
    },
    ...customConfig
  }

  if (config.method.toUpperCase() === 'GET') {
    endpoint+= `?${qs.stringify(data)}`
  } else {
    config.body = JSON.stringify(data || {})
  }
  return window.fetch(`${appUrl}/${endpoint}`, config).then(async response => {
    if (response.status === 401) {
      await auth.logout()
      window.location.reload()
      return Promise.reject({message: '请重新登录'})
    }
    const data = await response.json()
    if (response.ok) {
      return data
    } else {
      return Promise.reject(data)
    }
  })
}
// 添加token的请求
export const useHttp = () => {
  const {user} = useAuth()
  return useCallback(
    (...[endpoint, config]: Parameters<typeof http>) => http(endpoint, {...config, token: user?.token})
    , [user?.token])
}

// interface 也无法实现Utility type
// type Person = {
//   name: string,
//   age: number
// }

//
// const xiaoming: Partial<Person> = {}
//
// const person: Required<Person> = {
//   name: 'y',
//   age: 18
// }
//
// const shenMiRen: Omit<Person, 'name' | 'age'> = {}
